#!/usr/bin/python3
import os
from os.path import abspath
from tkinter import *
from tkinter import filedialog
import time
import subprocess
LOG_LINE_NUM = 0

class MY_GUI():
    def __init__(self,init_window_name):
        self.init_window_name = init_window_name
    #设置窗口
    def set_init_window(self):
        self.init_window_name.title("MP4转M3U8工具_v1.0")           #窗口名
        self.init_window_name.geometry('320x200') #290 160为窗口大小，+10 +10 定义窗口弹出时的默认展示位置
        
        #self.init_window_name["bg"] = "pink"                                    #窗口背景色，其他背景色见：blog.csdn.net/chl0000/article/details/7657887
        self.init_window_name.attributes("-alpha",0.9)                          #虚化，值越小虚化程度越高
        #标签
        self.init_data_label = Label(self.init_window_name,text="MP4视频",width = 10,height = 4)
        self.init_data_label.place(x = 20,y = 20,width = 80,height = 23)
        self.log_label = Label(self.init_window_name, text="分辨率",width = 10,height = 4)
        self.log_label.place(x = 20,y = 50,width = 80,height = 23)
        self.result_data_label = Label(self.init_window_name, text="执行日志",width = 10,height = 4)
        self.result_data_label.place(x = 10,y = 86,width = 100,height = 20)
		
        self.Label_fbl= Label(self.init_window_name,text="X",width = 10,height = 4)
        self.Label_fbl.place(x = 150,y = 55,width = 23,height = 20)
		
        #文本框
        self.video_path = StringVar()
        self.init_data_video = Entry(self.init_window_name, textvariable=self.video_path)  #原始数据录入框
        self.init_data_video.place(x = 101,y = 23,width = 100,height = 23)
		
        self.fbl_x = StringVar()
        self.init_fbl_x = Entry(self.init_window_name, textvariable=self.fbl_x)  #像素x
        self.init_fbl_x.place(x = 100,y = 55,width = 50,height = 20)
        self.fbl_x.set('640')
        
        self.fbl_y = StringVar()
        self.init_fbl_y = Entry(self.init_window_name, textvariable=self.fbl_y)  #像素y
        self.init_fbl_y.place(x = 173,y = 55,width = 50,height = 20)
        self.fbl_y.set("360")
				
        self.log_data_Text = Text(self.init_window_name, width=66, height=9)  # 日志框
        self.log_data_Text.place(x = 10,y = 120,width = 300,height = 70) 
        
        #按钮		
        self.str_trans_button = Button(self.init_window_name, text="转换", bg="lightblue", width=10,command=self.trans_video)
        self.str_trans_button.place(x = 100,y = 86,width = 80,height = 24)
        self.str_select_button = Button(self.init_window_name,text="选择",width = 10,height = 4,command = self.pathCallBack)
        self.str_select_button.place(x = 208,y = 23,width = 60,height = 24)
    def pathCallBack(self):
        filePath=filedialog.askopenfilename(title='Open MP4 File',filetypes=[('MP4 File','*.mp4'),('All files','*')])
        if(filePath != ''):
            self.video_path.set(filePath)	
    #功能函数
    def trans_video(self):
        video_path = self.video_path.get().strip().replace("\n","").encode()
        fbl_x = self.fbl_x.get().encode()+b'x'
        fbl_y = self.fbl_y.get().encode()
        fbl =  fbl_x+fbl_y
        if video_path:
            #try:
            ret = os.access(os.getcwd()+"/ffmpeg.exe", os.X_OK)
            if ret:
                getcwd = os.getcwd()
                video_name = video_path[0:-4].decode()
                joinpath = os.path.join(getcwd, "mp4")
                base_path = os.path.join(os.path.join(getcwd, "mp4"), video_name+'.m3u8')
                self.write_log_to_Text(base_path)
                cmd = [getcwd+"/ffmpeg.exe",'-i',video_path, '-profile:v', 'baseline', '-level', '3.0', '-s', fbl , '-start_number', '0', '-hls_time', '10', '-hls_list_size', '0', '-f', 'hls', base_path]
                self.write_log_to_Text('开始转换')
                process = subprocess.Popen(cmd,shell=True, stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,encoding="utf-8",text=True)
                self.write_log_to_Text('转换中')
                for line in process.stdout:
                    self.write_log_to_Text(line)
                #输出到界面
                self.write_log_to_Text("转换完成")
            else:
                self.write_log_to_Text("ffmpeg.exe文件不存在或不可写")
                return;
            #except:
            #    self.write_log_to_Text("ERROR:转换失败")
        else:
            self.write_log_to_Text("ERROR:请先选择视频")
        

    #获取当前时间
    def get_current_time(self):
        current_time = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
        return current_time


    #日志动态打印
    def write_log_to_Text(self,logmsg):
    
        
        global LOG_LINE_NUM
        current_time = self.get_current_time()
        logmsg_in = str(current_time) +" " + str(logmsg) + "\n"      #换行
        if LOG_LINE_NUM <= 7:
            self.log_data_Text.insert(END, logmsg_in)
            LOG_LINE_NUM = LOG_LINE_NUM + 1
        else:
            self.log_data_Text.delete(1.0,2.0)
            self.log_data_Text.insert(END, logmsg_in)
        


def gui_start():
    init_window = Tk()           #实例化出一个父窗口
    ZMJ_PORTAL = MY_GUI(init_window)
    # 设置根窗口默认属性
    ZMJ_PORTAL.set_init_window()

    init_window.mainloop()          #父窗口进入事件循环，可以理解为保持窗口运行，否则界面不展示


gui_start()